/**
 * +----------------------------------------------------------------------
 * | @Author: codeavatar   @Year：2021
 * +----------------------------------------------------------------------
 * | @Email: codeavatar@aliyun.com
 * +----------------------------------------------------------------------
 **/
//加载系统配置文件
const appconfig = require('./appconfig.js');
const applog = require('./utils/fwlog.js');
const apptool = require('./utils/fwtool.js');
const appauth = require('./utils/fwauthority.js');
const appmd5 = require('./utils/fwmd5.js');
const appsign = require('./utils/fwsign.js');
const appwechat = require('./utils/fwwechat.js');
const apputil = require('./utils/fwutil.js');

//整个项目仅限一个App()函数
App({
  onLaunch(options) {
    // Do something initial when launch.
    applog.info('Do something initial when launch.');
    this.initSys();
    this.loadJs();
    //设置模拟登录
    this.virtualLogin();
  },
  onShow(options) {
    // Do something when show.
    applog.info('Do something when show.');
    //场景值列表：https://developers.weixin.qq.com/miniprogram/dev/reference/scene-list.html
    //options.scene|options.query|options.path|options.shareTicket|options.referrerInfo
  },
  onHide() {
    // Do something when hide.
    applog.info('Do something when hide.');
  },
  onError(msg) {
    applog.error(msg);
  },

  globalData: {
    //全局控制
    wxmp_audit_switcher:false,
    wxmp_login_enabled:true,
    wxmp_check_offline:true, //离线检测
    //设置跳转路径,以'|'分隔的路径
    navigatePath:'',
    statebar_height:0,
    scrollview_height:0,
    disabled_operate_tip:'当前身份不支持该操作！',
    privacyRef:null, //隐私引用
  },
  
  initSys:function(){
    //获取设备顶部窗口的高度（不同设备窗口高度不一样，根据这个来设置自定义导航栏的高度
    wx.getSystemInfo({
      success: (res) => {
        this.globalData.statebar_height = res.statusBarHeight;
        this.globalData.scrollview_height = res.windowHeight-res.statusBarHeight-45;
      }
    });
  },

  loadJs: function () {
    this.appconfig = appconfig;
    this.applog = applog;
    this.apptool = apptool;
    this.appauth = appauth;
    this.appmd5 = appmd5;
    this.appsign = appsign;
    this.appwechat = appwechat;
    this.apputil = apputil;
  },
  
  _post:function(api, params, isCustomSuccess, successcallback, failcallback, completecallback){
    this._api(api, params, 'POST', function (res) {
      //执行成功
      if(isCustomSuccess && isCustomSuccess===true){
        successcallback && successcallback(res);
      }else{
        if (res.caCode === appconfig.fwcode.successed) {
          successcallback && successcallback(res.caData, res);
        } else {
            apptool.showToastInfo(res.caMsg);
        }
      }
    }, function (err) {
      //执行失败
      failcallback && failcallback(err);
    }, function (res) {
      //执行完成
      completecallback && completecallback(res);
    });
  },

  _get:function(api, params, isCustomSuccess, successcallback, failcallback, completecallback){
    this._api(api, params, 'GET', function (res) {
      //执行成功
      if(isCustomSuccess && isCustomSuccess===true){
        successcallback && successcallback(res);
      }else{
        if (res.caCode === appconfig.fwcode.successed) {
          successcallback && successcallback(res.caData, res);
        } else {
            apptool.showToastInfo(res.caMsg);
        }
      }
    }, function (err) {
      //执行失败
      failcallback && failcallback(err);
    }, function (res) {
      //执行完成
      completecallback && completecallback(res);
    });
  },

  _del:function(api, params, isCustomSuccess, successcallback, failcallback, completecallback){
    this._api(api, params, 'DELETE', function (res) {
      //执行成功
      if(isCustomSuccess && isCustomSuccess===true){
        successcallback && successcallback(res);
      }else{
        if (res.caCode === appconfig.fwcode.successed) {
          successcallback && successcallback(res.caData, res);
        } else {
            apptool.showToastInfo(res.caMsg);
        }
      }
    }, function (err) {
      //执行失败
      failcallback && failcallback(err);
    }, function (res) {
      //执行完成
      completecallback && completecallback(res);
    });
  },

  _api: function (api, params, method, successcallback, failcallback, completecallback){
    //==============公用参数 开始====================
    //过滤非object参数(null,'',undefined)
    if (typeof params !== 'object') { params = {}; }
    //(固定参数)
    params.caPlatform = this.appconfig.fwplatform;
    params.caDevice = this.appconfig.fwdevice;
    params.caVersion = this.appconfig.fwversion;
    //(请求头参数)
    let headers = {};
    //(用户身份参数)
    let authInfo = this.appauth.getAuthInfo();
    if (authInfo) {
      params.caUserId = authInfo.userId;
      params.caUserToken = authInfo.userToken;
      params.caUserType = authInfo.userType;
      //请求头数据
      headers['token'] = authInfo.userToken;
    }
    //==============公用参数 结束====================
    //组建API地址
    let requestAPI = this.appconfig.fwrootapi + api;
    //请求签名
    params.caRndstr = appsign.createRndStr(32);
    params.caRndnum = appsign.createRndNum(32);
    params.caTimestamp = appsign.createTimeStamp();
    params.caSign = appsign.makeSign(params, this.appconfig.keysecret);
    
    apptool.requestApi(requestAPI, params, method, headers, successcallback, function(){
      apptool.showModalInfo('网络异常！');  
      failcallback && failcallback();
    }, completecallback, this);
  },

  //组装网址
  _weburl(path,hasAuth,isWeb){
    let weburl = '';
    if(hasAuth === true){
      //(用户身份参数)
      let authInfo = this.appauth.getAuthInfo();
      weburl = this.appconfig.fwrootapi + path+'?token='+authInfo.userToken;
    }else{
      weburl = this.appconfig.fwrootapi + path;
    }
    //网页地址
    if(isWeb && isWeb===true){
        weburl += (-1 != weburl.lastIndexOf('?')?'&':'?')+Math.random();
    }
    return weburl;
  },

   //在线检测（若已失效，则清除登录数据）
   _checkOnline:function(successcallback, failcallback, completedcallback){
    let _this = this;
    this.globalData.wxmp_check_offline = false;
    this._post('/Action/checkOnline', {}, true, function (res) {
      if (res.caCode == appconfig.fwcode.nologin) {
        _this.appauth.clearUserCacheData();
        successcallback && successcallback();
        return;
      }
    }, function (res) {
      //执行失败
      _this.applog.error(res);
      failcallback && failcallback();
    }, function (res) {
      //执行完成
      _this.globalData.wxmp_check_offline = true;
      completedcallback && completedcallback();
    });
  },

  // 检测登录
  _checkLogin:function(refresh){
    let loginStatus = this.appauth.checkAuth();
    if (!loginStatus){
      apptool.showToastInfo('请登录后再操作！',null,1000,function(res){
        //如果需要回调，则必须在当前面实现 refreshPage() 方法
        wx.navigateTo({
          url: '/pages/basic/login' + (refresh ? '?refresh=2' : '?refresh=1'),
        });
      });
    }
    return loginStatus;
  },

  // 模拟帐号
  virtualLogin:function(){
    if ((appconfig.release==false) && appconfig.testData.isOpenTest) {
        //身份数据缓存到本地
        appauth.setUserCacheData({
            user_id: appconfig.testData.testUserId,
            user_token: appconfig.testData.testUserToken,
            nickname: '模拟帐号',
            avatar: '/pages/res/common/icon_owner_portrait.png',
            mobile: '15512345678'
        });
    }
  }

})